const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken');

const app = express();
const PORT = process.env.PORT || 3000;

// 中间件
app.use(cors());
app.use(bodyParser.json());

// 用户数据（与前端Mock数据保持一致）
const userData = {
  userToken: [
    {
      token: "AshgytoHgaGTiahfkljg",
      userId: "dabai",
      password: "123456"
    },
    {
      token: "HasdfPIasdfASHasdfDF",
      userId: "xiaobai",
      password: "000000"
    },
    {
      token: "aoFGligGHhsSHuJihoJUia",
      userId: "1",
      password: "111111"
    }
  ],
  userInfo: [
    {
      userName: "大白",
      role: "管理员",
      portrait: "/user-portrait/dabai.jpg",
      userId: "dabai"
    },
    {
      userName: "小白",
      role: "会员",
      portrait: "/user-portrait/xiaobai.jpg",
      userId: "xiaobai"
    },
    {
      userName: "测试",
      role: "测试",
      portrait: "/user-portrait/test.jpg",
      userId: "1"
    }
  ]
};

// 登录接口
app.post('/mock/token', (req, res) => {
  const { userName, password } = req.body;
  
  const userInfo = userData.userToken.filter((u) => {
    return u.userId === userName && u.password === password;
  });
  
  if (userInfo.length) {
    res.json({ code: 200, data: userInfo[0].token });
  } else {
    res.json({ code: 201, message: '用户名或密码不正确' });
  }
});

// 获取用户信息接口
app.post('/mock/userinfo', (req, res) => {
  const { token } = req.body;
  
  const findUserToken = userData.userToken.find((item) => item.token === token);
  if (findUserToken) {
    const findUserInfo = userData.userInfo.find((item) => item.userId === findUserToken.userId);
    res.json({ code: 200, data: findUserInfo });
  } else {
    res.json({ code: 201, message: 'token已失效' });
  }
});

// 健康检查接口
app.get('/health', (req, res) => {
  res.json({ status: 'ok', message: 'Vue3管理后端服务运行正常' });
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`后端服务已启动，端口: ${PORT}`);
  console.log(`健康检查: http://localhost:${PORT}/health`);
});
